﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DblogStudio.BLL;
using DblogStudio.DAL.Models;
using DblogStudio.GUI.Common;
using DblogStudio.GUI.Utils;
namespace DblogStudio.GUI.TacNghiep
{
    public partial class FormDanhSachCanhBao : BaseDialog
    {

        public FormDanhSachCanhBao()
        {
            InitializeComponent();
            InitGrid();
            LoadDanhSachCanBaoTri();
            InitTree();
        }

        private void InitGrid()
        {
            gridData.AutoGenerateColumns = false;
            gridData.AddRowIndexing();
            gridDataDangCay.AutoGenerateColumns = false;
            gridDataDangCay.AddRowIndexing();
            gridHistoryData.AutoGenerateColumns = false;
            gridHistoryData.AddRowIndexing();
        }

        private void LoadDanhSachCanBaoTri()
        {
            List<LichBaoTriCustom> ls = new List<LichBaoTriCustom>();
            int dsCanhBao = int.Parse(BizAppConfig.GetDSCanhBaoDesktop());
            var frm = new FormProgress();
            frm.DoWork += (o, t) =>
            {
                ls = BizLichBaoTri.GetList(dsCanhBao, FormMain.NguoiSuDung.Role == (int)VAITRO.NhanVienBaoTri ? FormMain.NguoiSuDung.UserName : "");
            };
            frm.RunWorkerCompleted += (o, t) =>
            {
                bsData.DataSource = new MySortableBindingList<LichBaoTriCustom>(ls);
                gridData.DataSource = bsData;
            };
            frm.StartWorking(this);
        }

        bool allowReLoad = false;
        private DataGridViewCellStyle m_TruocHanStyle = null;
        private DataGridViewCellStyle TruocHanStyle
        {
            get
            {
                if (m_TruocHanStyle == null)
                {
                    m_TruocHanStyle = new DataGridViewCellStyle(gridData.DefaultCellStyle);
                    m_TruocHanStyle.Font = new Font(gridData.Font, FontStyle.Regular);
                    m_TruocHanStyle.BackColor = Color.FromArgb(int.Parse(BizAppConfig.GetMAUTRUOCHAN()));
                    m_TruocHanStyle.ForeColor = Color.White;
                }
                return m_TruocHanStyle;
            }
        }
        private DataGridViewCellStyle m_ToiHanStyle = null;
        private DataGridViewCellStyle ToiHanStyle
        {
            get
            {
                if (m_ToiHanStyle == null)
                {
                    m_ToiHanStyle = new DataGridViewCellStyle(gridData.DefaultCellStyle);
                    m_ToiHanStyle.Font = new Font(gridData.Font, FontStyle.Regular);
                    m_ToiHanStyle.BackColor = Color.FromArgb(int.Parse(BizAppConfig.GetMAUTOIHAN()));
                    m_ToiHanStyle.ForeColor = Color.White;
                }
                return m_ToiHanStyle;
            }
        }
        private DataGridViewCellStyle m_QuaHan30Style = null;
        private DataGridViewCellStyle QuaHan30Style
        {
            get
            {
                if (m_QuaHan30Style == null)
                {
                    m_QuaHan30Style = new DataGridViewCellStyle(gridData.DefaultCellStyle);
                    m_QuaHan30Style.Font = new Font(gridData.Font, FontStyle.Regular);
                    m_QuaHan30Style.BackColor = Color.FromArgb(int.Parse(BizAppConfig.GetMAUQUAHANDUOI30()));
                    m_QuaHan30Style.ForeColor = Color.White;
                }
                return m_QuaHan30Style;
            }
        }
        private DataGridViewCellStyle m_QuaHanStyle = null;
        private DataGridViewCellStyle QuaHanStyle
        {
            get
            {
                if (m_QuaHanStyle == null)
                {
                    m_QuaHanStyle = new DataGridViewCellStyle(gridData.DefaultCellStyle);
                    m_QuaHanStyle.Font = new Font(gridData.Font, FontStyle.Regular);
                    m_QuaHanStyle.BackColor = Color.FromArgb(int.Parse(BizAppConfig.GetMAUQUAHAN()));
                    m_QuaHanStyle.ForeColor = Color.White;
                }
                return m_QuaHanStyle;
            }
        }

        private void gridData_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            for (int i = 0; i < gridData.Rows.Count; i++)
            {
                DataGridViewRow dgrow = gridData.Rows[i];
                var lichBaoTri = dgrow.DataBoundItem as LichBaoTriCustom;

                for (int j = 0; j <= colQuaHan.Index; j++)
                    if (lichBaoTri._QuaHan < 0)
                        dgrow.Cells[j].Style = TruocHanStyle;
                    else if (lichBaoTri._QuaHan == 0)
                        dgrow.Cells[j].Style = ToiHanStyle;
                    else if (lichBaoTri._QuaHan > 0)
                    {
                        if (lichBaoTri._QuaHan <= 0.3 * lichBaoTri.ChuKy)
                            dgrow.Cells[j].Style = QuaHan30Style;
                        else
                            dgrow.Cells[j].Style = QuaHanStyle;
                    }
            }
        }

        private void gridDataDangCay_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            for (int i = 0; i < gridDataDangCay.Rows.Count; i++)
            {
                DataGridViewRow dgrow = gridDataDangCay.Rows[i];
                var lichBaoTri = dgrow.DataBoundItem as LichBaoTri;

                for (int j = 0; j <= colGhiChu.Index; j++)
                    if (lichBaoTri._QuaHan < 0)
                        dgrow.Cells[j].Style = TruocHanStyle;
                    else if (lichBaoTri._QuaHan == 0)
                        dgrow.Cells[j].Style = ToiHanStyle;
                    else if (lichBaoTri._QuaHan > 0)
                    {
                        if (lichBaoTri._QuaHan <= 0.3 * lichBaoTri.ChuKy)
                            dgrow.Cells[j].Style = QuaHan30Style;
                        else
                            dgrow.Cells[j].Style = QuaHanStyle;
                    }
            }
        }

        private void gridData_Sorted(object sender, EventArgs e)
        {
            gridData_DataBindingComplete(sender, null);
        }

        private void btnBaoTri_Click(object sender, EventArgs e)
        {
            var current = bsData.Current as LichBaoTriCustom;
            if (current != null)
            {
                var frm = new FormBaoTri(current);
                frm.OnChanged += (o, t) =>
                {
                    LoadDanhSachCanBaoTri();
                    LoadLichBaoTri(current.MaChiTietMay);
                    LoadLichSuBaoTri(current.MaChiTietMay);
                    //UpdateTree(current.MaChiTietMay);
                    InitTree();
                    this.Refresh();
                };
                frm.ShowDialog();
            }
        }

        private void btnBaoTriTabCay_Click(object sender, EventArgs e)
        {
            var current = bsLichBaoTri.Current as LichBaoTri;
            if (current != null)
            {
                var frm = new FormBaoTri(current);
                frm.OnChanged += (o, t) =>
                {
                    LoadDanhSachCanBaoTri();
                    if (treeChiTietMay.SelectedNode.Level == 1)
                        LoadLichBaoTriTheoMay(treeChiTietMay.SelectedNode.Tag.ToString());
                    else
                    {
                        LoadLichBaoTri(current.MaChiTietMay);
                        LoadLichSuBaoTri(current.MaChiTietMay);
                    }
                    UpdateTree(current.MaChiTietMay);
                    this.Refresh();
                };
                frm.ShowDialog();
            }
        }

        private void InitTree()
        {
            #region Khởi tạo cây
            treeChiTietMay.Nodes.Clear();
            var boldFont = new System.Drawing.Font(treeChiTietMay.Font, FontStyle.Bold);
            var allowAdmin = FormMain.NguoiSuDung.Role == (int)VAITRO.Admin;
            var manv = FormMain.NguoiSuDung.UserName;
            if (allowAdmin)
                manv = "";
            var lsCongDoan = BizCongDoanSanXuat.GetList();
            if (lsCongDoan != null && lsCongDoan.Count > 0)
            {
                foreach (var congDoan in lsCongDoan)
                {
                    if (!allowAdmin)
                        if (!BizPhanCongBaoTri.CheckPermissionForCongDoan(manv, congDoan.MaCongDoanSanXuat))
                            continue;
                    int trongHan = 0;
                    int quaHan = 0;
                    int truocHan = 0;
                    BizCongDoanSanXuat.GetStatisCanhBao(congDoan.MaCongDoanSanXuat, out quaHan, out trongHan, out truocHan, manv);
                    var nodeCongDoan = new TreeNode(congDoan.TenCongDoanSanXuat + string.Format(" ({0}/{1}/{2})", quaHan, trongHan, truocHan));
                    nodeCongDoan.Tag = congDoan.MaCongDoanSanXuat;
                    nodeCongDoan.NodeFont = boldFont;
                    nodeCongDoan.Nodes.Add("...");
                    treeChiTietMay.Nodes.Add(nodeCongDoan);
                }
            }
            #endregion
        }

        private void treeChiTietMay_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            var manv = FormMain.NguoiSuDung.UserName;
            var allowAdmin = FormMain.NguoiSuDung.Role == (int)VAITRO.Admin;
            if (allowAdmin)
                manv = "";
            if (e.Node.Nodes.Count == 0 || e.Node.Nodes[0].Text == "..." || allowReLoad)
            {
                if (e.Node.Level == 0)
                {
                    //Node đang chọn là công đoạn sản xuất ==> Load máy sản xuất của công đoạn tương ứng

                    e.Node.Nodes.Clear();
                    var congDoan = BizCongDoanSanXuat.GetByID(e.Node.Tag.ToString());
                    if (congDoan != null)
                    {
                        var lsMaySanXuat = BizMaySanXuat.GetList(congDoan.MaCongDoanSanXuat);
                        if (lsMaySanXuat != null && lsMaySanXuat.Count > 0)
                        {
                            foreach (var maySanXuat in lsMaySanXuat)
                            {
                                if (!allowAdmin)
                                    if (!BizPhanCongBaoTri.CheckPermissionForMaySanXuat(manv, maySanXuat.MaMaySanXuat))
                                        continue;

                                int trongHan = 0;
                                int quaHan = 0;
                                int truocHan = 0;
                                BizMaySanXuat.GetStatisCanhBao(maySanXuat.MaMaySanXuat, out quaHan, out trongHan, out truocHan, manv);
                                var nodeMaySanXuat = new TreeNode(maySanXuat.TenMaySanXuat + string.Format(" ({0}/{1}/{2})", quaHan, trongHan, truocHan));
                                nodeMaySanXuat.Tag = maySanXuat.MaMaySanXuat;
                                nodeMaySanXuat.Nodes.Add("...");
                                e.Node.Nodes.Add(nodeMaySanXuat);
                            }
                        }
                    }
                }
                else if (e.Node.Level == 1)
                {
                    //Node đang chọn là node máy sản xuất ==> Load Bộ phận sản xuất
                    e.Node.Nodes.Clear();
                    var maySanXuat = BizMaySanXuat.GetByID(e.Node.Tag.ToString());
                    if (maySanXuat != null)
                    {
                        var lsBoPhanMay = BizBoPhanMay.GetList(maySanXuat.MaMaySanXuat);
                        if (lsBoPhanMay != null && lsBoPhanMay.Count > 0)
                        {
                            foreach (var boPhanMay in lsBoPhanMay)
                            {
                                if (!allowAdmin)
                                    if (!BizPhanCongBaoTri.CheckPermissionForBoPhanMay(manv, boPhanMay.MaBoPhanMay))
                                        continue;
                                int trongHan = 0;
                                int quaHan = 0;
                                int truocHan = 0;
                                BizBoPhanMay.GetStatisCanhBao(boPhanMay.MaBoPhanMay, out quaHan, out trongHan, out truocHan, manv);
                                var nodeBoPhanMay = new TreeNode(boPhanMay.TenBoPhanMay + string.Format(" ({0}/{1}/{2})", quaHan, trongHan, truocHan));
                                nodeBoPhanMay.Tag = boPhanMay.MaBoPhanMay;
                                nodeBoPhanMay.Nodes.Add("...");

                                e.Node.Nodes.Add(nodeBoPhanMay);
                            }
                        }
                    }
                }
                else if (e.Node.Level == 2)
                {
                    //Node đang chọn là node bộ phận sản xuất ==> Load Chi tiết máy
                    e.Node.Nodes.Clear();
                    var boPhanMay = BizBoPhanMay.GetByID(e.Node.Tag.ToString());
                    if (boPhanMay != null)
                    {
                        var lsChiTietMay = BizChiTietMay.GetList(boPhanMay.MaBoPhanMay);
                        if (lsChiTietMay != null && lsChiTietMay.Count > 0)
                        {
                            var italicFont = new System.Drawing.Font(treeChiTietMay.Font, FontStyle.Italic);
                            foreach (var chiTietMay in lsChiTietMay)
                            {
                                if (!allowAdmin)
                                    if (!BizPhanCongBaoTri.CheckPermissionForChiTietMay(manv, chiTietMay.MaChiTietMay))
                                        continue;
                                int trongHan = 0;
                                int quaHan = 0;
                                int truocHan = 0;
                                BizChiTietMay.GetStatisCanhBao(chiTietMay.MaChiTietMay, out quaHan, out trongHan, out truocHan, manv);
                                var nodeChiTietMay = new TreeNode(chiTietMay.TenChiTietMay + string.Format(" ({0}/{1}/{2})", quaHan, trongHan, truocHan));
                                nodeChiTietMay.Tag = chiTietMay.MaChiTietMay;
                                nodeChiTietMay.NodeFont = italicFont;
                                e.Node.Nodes.Add(nodeChiTietMay);
                            }
                        }
                    }
                }
            }
        }

        private void treeChiTietMay_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeChiTietMay.SelectedNode.Level == 3)
            {
                lbChiTietMay.Text = treeChiTietMay.SelectedNode.Text;
                LoadLichBaoTri(treeChiTietMay.SelectedNode.Tag.ToString());
                LoadLichSuBaoTri(treeChiTietMay.SelectedNode.Tag.ToString());
            }
            else if (treeChiTietMay.SelectedNode.Level == 1)
            {
                lbChiTietMay.Text = treeChiTietMay.SelectedNode.Text;
                LoadLichBaoTriTheoMay(treeChiTietMay.SelectedNode.Tag.ToString());
                //LoadLichSuBaoTri(treeChiTietMay.SelectedNode.Tag.ToString());
                bsLichSuBaoTri.DataSource = null;
                gridHistoryData.DataSource = bsLichSuBaoTri;
            }
            else
            {
                lbChiTietMay.Text = "Chi tiết máy:...";
                bsLichBaoTri.DataSource = null;
                gridDataDangCay.DataSource = bsLichBaoTri;
                bsLichSuBaoTri.DataSource = null;
                gridHistoryData.DataSource = bsLichSuBaoTri;
            }
        }

        private void LoadLichBaoTri(string maChiTietMay)
        {
            var lsLichBaoTri = BizLichBaoTri.GetList(maChiTietMay);
            bsLichBaoTri.DataSource = lsLichBaoTri;
            gridDataDangCay.DataSource = bsLichBaoTri;
        }
        private void LoadLichBaoTriTheoMay(string maMay)
        {
            var lsLichBaoTri = BizLichBaoTri.GetListTheoMay(maMay);
            bsLichBaoTri.DataSource = lsLichBaoTri;
            gridDataDangCay.DataSource = bsLichBaoTri;
        }

        private void LoadLichSuBaoTri(string maChiTietMay)
        {
            var lsLichSuBaoTri = BizLichSuBaoTri.GetList(maChiTietMay);
            bsLichSuBaoTri.DataSource = new MySortableBindingList<LichSuBaoTri>(lsLichSuBaoTri);
            gridHistoryData.DataSource = bsLichSuBaoTri;
        }

        private void bsLichBaoTri_CurrentChanged(object sender, EventArgs e)
        {
            var current = bsLichBaoTri.Current as LichBaoTri;
            if (current != null)
            {

            }
        }

        private void btnRefesh_Click(object sender, EventArgs e)
        {
            allowReLoad = true;
            InitTree();
            allowReLoad = false;
        }

        private void UpdateTree(string maChiTietMay)
        {
            var ctm = BizChiTietMay.GetByID(maChiTietMay);
            if (ctm == null)
                throw new Exception("Không tìm thấy chi tiết máy");
            var node = GetNode(ctm.MaChiTietMay);
            if (node != null)
            {
                int trongHan = 0;
                int quaHan = 0;
                int truocHan = 0;
                BizChiTietMay.GetStatisCanhBao(ctm.MaChiTietMay, out quaHan, out trongHan, out truocHan);
                node.Text = ctm.TenChiTietMay + string.Format(" ({0}/{1}/{2})", quaHan, trongHan, truocHan);
                lbChiTietMay.Text = node.Text;
            }
            var bpm = BizBoPhanMay.GetByID(ctm.MaBoPhanMay);
            if (bpm == null)
                throw new Exception("Không tìm thấy bộ phận máy");
            node = GetNode(bpm.MaBoPhanMay);
            if (node != null)
            {
                int trongHan = 0;
                int quaHan = 0;
                int truocHan = 0;
                BizBoPhanMay.GetStatisCanhBao(bpm.MaBoPhanMay, out quaHan, out trongHan, out truocHan);
                node.Text = bpm.TenBoPhanMay + string.Format(" ({0}/{1}/{2})", quaHan, trongHan, truocHan);
            }
            var msx = BizMaySanXuat.GetByID(bpm.MaMaySanXuat);
            if (msx == null)
                throw new Exception("Không tìm thấy máy sản xuất");
            node = GetNode(msx.MaMaySanXuat);
            if (node != null)
            {
                int trongHan = 0;
                int quaHan = 0;
                int truocHan = 0;
                BizMaySanXuat.GetStatisCanhBao(msx.MaMaySanXuat, out quaHan, out trongHan, out truocHan);
                node.Text = msx.TenMaySanXuat + string.Format(" ({0}/{1}/{2})", quaHan, trongHan, truocHan);
            }
            var cd = BizCongDoanSanXuat.GetByID(msx.MaCongDoanSanXuat);
            if (cd == null)
                throw new Exception("Không tìm thấy công đoạn");
            node = GetNode(cd.MaCongDoanSanXuat);
            if (node != null)
            {
                int trongHan = 0;
                int quaHan = 0;
                int truocHan = 0;
                BizCongDoanSanXuat.GetStatisCanhBao(cd.MaCongDoanSanXuat, out quaHan, out trongHan, out truocHan);
                node.Text = cd.TenCongDoanSanXuat + string.Format(" ({0}/{1}/{2})", quaHan, trongHan, truocHan);
            }
        }

        public TreeNode GetNode(string id, TreeNode rootNode)
        {
            foreach (TreeNode node in rootNode.Nodes)
            {
                if (node.Tag != null)
                    if (node.Tag.Equals(id)) return node;
                TreeNode next = GetNode(id, node);
                if (next != null) return next;
            }
            return null;
        }

        public TreeNode GetNode(string id)
        {
            TreeNode itemNode = null;
            foreach (TreeNode node in treeChiTietMay.Nodes)
            {
                if (node.Tag != null)
                    if (node.Tag.Equals(id)) return node;
                itemNode = GetNode(id, node);
                if (itemNode != null) break;
            }
            return itemNode;
        }
    }
}
